<template>
  <div>
    <common-scroll class="city-wrap"
                   ref="scroll"
                   :data="hot"
                   @scroll="scroll"
                   :listenScroll="listenScroll"
                   :probeType="probeType">
      <div>
        <div class="area">
          <div class="area-title">当前城市：</div>
          <div class="city-name-wrap"
               border-radius>
            <span class="city-name">{{this.city}}</span>
          </div>
        </div>
        <div class="area">
          <div class="area-title">定位/最近访问</div>
          <ul class="hot-city-list">
            <li class="hot-city-item"
                v-for="(item,index) of location"
                :key="index">
              <div class="city-name-wrap"
                   border-radius
                   @click="handleChangeCity(item)">
                <span class="city-name">{{item}}</span>
              </div>
            </li>
          </ul>
        </div>
        <div class="area"
             ref="hot">
          <div class="area-title">热门城市</div>
          <ul class="hot-city-list">
            <li class="hot-city-item"
                v-for="item of hot"
                :key="item.id">
              <div class="city-name-wrap"
                   border-radius
                   @click="handleChangeCity(item.name)">
                <span class="city-name">{{item.name}}</span>
              </div>
            </li>
          </ul>
        </div>
        <div class="all-city-area">
          <div class="area-title">所有城市</div>
          <div class="alphabet-area"
               v-for="(item, key) of cities"
               :key="key"
               ref="listGroup">
            <div class="all-city-title"
                 border-top-1px>{{key}}</div>
            <ul class="all-city-wrap">
              <li class="all-city-item"
                  border-top-1px
                  v-for="innerItem of item"
                  :key="innerItem.id"
                  @click="handleChangeCity(innerItem.name)">
                {{innerItem.name}}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </common-scroll>
    <city-alphabet :cities="cities"
                   @change="handleIndexChange"
                   :currentIndex="currentIndex"></city-alphabet>
    <el-amap vid="amap"
             :plugin="plugin"></el-amap>
  </div>
</template>

<script>
import CommonScroll from 'common/scroll/Scroll'
import CityAlphabet from './Alphabet'
import { mapState, mapActions, mapMutations } from 'vuex'
export default {
  name: 'CityLsit',
  components: {
    CommonScroll,
    CityAlphabet
  },
  props: {
    hot: {
      type: Array,
      default () {
        return []
      }
    },
    cities: {
      title: Object
    }
  },
  data () {
    let _this = this
    return {
      hots: this.hot,
      scrollY: -1,
      currentIndex: 0,
      probeType: 3,
      listenScroll: true,
      location: [],
      plugin: [{
        pName: 'Geolocation',
        events: {
          init (o) {
            _this.map = o
            // o 是高德地图定位插件实例
            return new Promise((resolve, reject) => {
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  resolve(result)
                } else {
                  reject(result)
                }
              })
            })
          }
        }
      }],
      locationCity: '',
      locationStreet: '',
      map: ''
    }
  },
  computed: {
    ...mapState(['city', 'historyCity'])
    // locationCities () {
    //   this.$localStorage.get('location')
    //   if()
    // }
  },
  created () {
    this.listHeight = []
  },
  methods: {
    handleChangeCity (city) {
      const CITY = '定位失败'
      if (city === CITY) {
        this.getLocation(this.map)
      } else {
        this.changeCity(city)
        this.$router.push('/')
        this.handleHistoryCity(city)
      }
    },
    handleHistoryCity (city) {
      let history = JSON.parse(this.$localStorage.get('history'))
      if (history !== null) {
        history.push(city)
        history = [...new Set(history)]
        this.$localStorage.set('history', JSON.stringify(history))
      } else {
        this.historyCity.push(city)
        let citys = [...new Set(this.historyCity)]
        this.$localStorage.set('history', JSON.stringify(citys))
      }
    },
    locationCities () {
      const cities = JSON.parse(this.$localStorage.get('history'))
      if (cities != null) {
        this.location = cities
      }
    },
    ...mapActions({
      changeCity: 'changeCity'
    }),
    ...mapMutations({
      changeHistoryCity: 'changeHistoryCity',
      changeStreet: 'changeStreet'

    }),
    handleIndexChange (index) {
      this.currentIndex = parseInt(index)
      index = parseInt(index)
      this.$refs.scroll.scrollToElement(this.$refs.listGroup[index], 1000)
    },
    scroll (pos) {
      this.scrollY = pos.y
    },
    _calculateHeight () {
      const list = this.$refs.listGroup
      this.listHeight = []
      const hotHeight = this.$refs.hot.offsetTop
      let height = hotHeight
      this.listHeight.push(height)
      for (let i = 0, len = list.length; i < len; i++) {
        const element = list[i]
        height += element.clientHeight
        this.listHeight.push(height)
      }
    },
    getLocation (o) {
      const events = this.plugin[0].events.init(o)
      events.then((res) => {
        o.options.maximumAge = 0
        let city = res.addressComponent.city
        let street = res.addressComponent.street
        city = city.substring(0, city.length - 1)
        this.$localStorage.set('city', city)
        this.$localStorage.set('LocationCity', city)
        this.locationCity = city
        this.locationStreet = street
        this.changeStreet(street)
        this.$localStorage.set('street', street)
        const sellerCity = this.$localStorage.get('city')
        const location = {
          local_city: city,
          select_city: sellerCity,
          longitude: res.position.O,
          latitude: res.position.P,
          page: 1
        }
        this.$localStorage.set('locationData', JSON.stringify(location))
      }).catch((e) => {
        window.close()
      })
    }
  },
  watch: {
    hot (hot) {
      setTimeout(() => {
        if (this.$refs.listGroup) {
          this._calculateHeight()
        }
      }, 20)
    },
    scrollY (newY) {
      const list = this.listHeight
      const hotHeight = this.$refs.hot.offsetTop
      if (newY > -hotHeight) {
        this.currentIndex = 0
        return
      }
      for (let i = 0, len = list.length - 1; i < len; i++) {
        let height1 = list[i]
        let height2 = list[i + 1]
        if (-newY > height1 && -newY < height2) {
          this.currentIndex = i
          return
        }
      }
      this.currentIndex = list.length - 2
    },
    locationCity (city) {
      let history = this.$localStorage.get('history')
      if (history !== null) {
        history = JSON.parse(history)
        history[0] = city
        history = [...new Set(history)]
        this.$localStorage.set('history', JSON.stringify(history))
      } else {
        this.$localStorage.set('LocationCity', city)
        const cities = []
        cities.push(city)
        this.$localStorage.set('history', JSON.stringify(cities))
      }
    },
    locationStreet (street) {
      this.$localStorage.set('street', street)
    }
  },
  activated () {
    this.$nextTick(() => {
      this.locationCities()
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/variable.styl'
@import '~stylus/mixins.styl'

.city-wrap
  top 212px

  .area
    padding-left 40px
    padding-right 40px
    box-sizing border-box
    margin-bottom 20px

  .area-title
    line-height 47px
    color #050505
    font-size $fzThird
    margin-bottom 20px

  .hot-city-list
    display flex
    flex-wrap wrap
    width 100%

    .hot-city-item
      width 25%
      background-color $bgcWh
      margin-bottom 20px

  .all-city-title
    width 100%
    background-color #f5f5f5
    text-indent 40px
    font-size $fzThird
    color $fzColor
    line-height 50px

  .all-city-wrap
    width 100%
    display flex
    flex-direction column
    justify-content center

    .all-city-item
      line-height 60px
      width 100%
      font-size $fzThird
      color $fzColor
      text-indent 40px
      padding-right 20px
      box-sizing border-box
      ellipsis()

  .city-name-wrap
    width 156px
    height 70px
    display flex
    justify-content center
    align-items center
    padding-left 10px
    padding-right 10px
    box-sizing border-box

    .city-name
      width 156px
      height 60px
      line-height 70px
      text-align center
      display block
      font-size $fzThird
      ellipsis()

  [border-radius]::before
    border-radius 60px
    border-color #DCDCDC

  .all-city-area
    width 100%

    .area-title
      text-indent 40px
</style>
